using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Main: MonoBehaviour
{
    public GameObject[] prefabs;
    public GameObject[,] objects;
    
    public int Column;
    public int Row;
    public float Size = 1;
    public float startTime = 1;
    List<GameObject> cache = new List<GameObject>();
    // Start is called before the first frame update
    void Start()
    {
        objects = new GameObject[Column, Row];
        int max = prefabs.Length;
        float sx = Column * -0.5f*Size+Size*0.5f;
        float sy = Row * -0.5f*Size+Size*0.5f;
        for (int i = 0; i < Column; i++)
        {
            for (int j = 0; j < Row; j++)
            {
                int index = Random.Range(0, max);
                GameObject go = GameObject.Instantiate(prefabs[index]);
                go.transform.SetParent(transform);
                go.transform.localPosition = new Vector3(i*Size + sx, j*Size + sy, 0);
                go.transform.localScale = new Vector3(Size, Size,Size);
                Mark mark = go.AddComponent<Mark>();
                mark.Column = i;
                mark.Row = j;
                mark.Index = index;
                go.name = index.ToString();
                go.AddComponent<BoxCollider2D>();
                objects[i, j] = go;
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (startTime > 0)
        {
            startTime -= Time.deltaTime;
        }
        if (startTime < 0)
        {
            if (Input.GetMouseButtonDown(0))
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
                if (hit.transform != null)
                {
                    Mark mark = hit.transform.GetComponent<Mark>();
                    cache.Clear();
                    Check(hit.transform.gameObject.name, mark.Column, mark.Row);
                    if (cache.Count >= 3)
                    {
                        PlayDestory();
                    }
                }
            }
        }
    }
    void Check(string type, int column, int row)
    {
        if (row < 0 | row >= Row || column < 0 || column >= Column)
            return;
        GameObject go = objects[column, row];
        if (go.name != type)
            return;
        if (cache.Contains(go))
            return;
        cache.Add(go);
        Check(type, column, row - 1);
        Check(type, column, row + 1);
        Check(type, column - 1, row);
        Check(type, column + 1, row);
    }
    void PlayDestory()
    {
        for (int i = 0; i < cache.Count; i++)
        {
            Mark mark = cache[i].GetComponent<Mark>();
            objects[mark.Column, mark.Row] = null;
            GameObject.Destroy(cache[i]);
        }
    }
}

